<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/excel')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :data="list" border :default-sort="{prop: 'timeOfEntry', order: 'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" style="width:100px; height:100px;">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式">
            <template #default="{row}">{{ hireTypeFormat(row.formOfEmployment) }}</template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[5, 10, 20, 100]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 创建弹窗 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <empDialog ref="empDialog" @success="hSuccess" @close="showDialog=false" />

      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog title="新增员工" :visible.sync="roleShowDialog">

        <AssignRole
          v-if="roleShowDialog"
          :role-id="roleId"
          @close="roleShowDialog=false"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getEmployeeList, delEmployeess } from '@/api/employess'
import employeesEnum from '@/constant/employees'
import empDialog from './empDialog.vue'
import AssignRole from './assignRole.vue'
console.log('12', employeesEnum.hireType)
// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
console.log('hireType', hireType)
export default {
  components: {
    empDialog,
    AssignRole

  },
  data() {
    return {
      roleId: '', // 接收当前角色的id信息
      roleShowDialog: false, // 控制角色分配角色
      showDialog: false, // 控制弹层
      list: [],
      page: 1, // 页码值
      size: 5, // 每页显示的条数
      total: 0// 员工的总数

    }
  },
  // 调用
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 获取id传给子组件得到当前的点击的id信息
    hAssignRole(id) {
      this.roleId = id
      this.roleShowDialog = true
    },
    // Object.values(item)  ["2018-11-20"]
    formatData(list) {
      // 1. 根据数据对象的健根据映射关系，得到一个中文的健，放到一个数组中  ---header ['编号', '密码']
      // 2. 将每一个对象的值，存到一个数组中，所有的结果放入到一个大的数组中--data  [["2018-11-30", "总裁办"],[]]
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      const one = list[0]
      // 如果list中有数组，才需要生成表头
      if (!one) return // 没有数据 直接终止
      const header = Object.keys(one).map(enkey => {
        return map[enkey]
      })

      // 2. 生成data数据
      const data = list.map(item => {
        return Object.values(item)
      })
      return { header: header, data: data }
    },
    async handleDownload() {
      // 发送axios
      try {
        const res = await getEmployeeList(this.page, this.size)
        if (res.code === 10000) {
          console.log(res.data.rows, 'res.data.rows')
          const { header, data } = this.formatData(res.data.rows)

          //  import('@/vendor/Export2Excel')  懒加载的方式读取一个文件（模块）返回是一个promise实例对象
          import('@/vendor/Export2Excel').then(excel => {
            // excel指的是模块对象(文件对象)，就可以直接调用文件中的任何函数或者使用文件中的任何变量  excel.函数名()   || excel.变量
            //  excel调用export_json_to_excel()
            excel.export_json_to_excel({
              header: header,
              data,
              filename: this.filename,
              autoWidth: this.autoWidth,
              bookType: this.bookType
            })
          })
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 删除数据
    hDel(id) {
      console.log(id)
      this.$confirm('您确定要删除此条数据嘛？').then(async() => {
        const res = await delEmployeess(id)
        if (this.list.length === 1) {
          this.page--
        }
        if (this.page <= 0) {
          this.page = 1
        }
        console.log(res)
        this.loadEmployeeList()
      }).catch(err => err)
    },
    // 重置表单
    hClose() {
      this.$refs.empDialog.resetForm()
    },
    // 重新渲染页面
    hSuccess() {
      // 获取最大的页码值
      this.total++
      const maxPage = Math.ceil(this.total / this.size)// 获取最大的页码值
      this.page = maxPage
      this.showDialog = false
      this.loadEmployeeList()
      // 关闭弹层
    },
    // 分页设置
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeeList()
    },
    // 返回的值
    hireTypeFormat(data) {
      // return employeesEnum.hireType.find(item => item.id === data).value
      return hireType[data] || '未知'
    },
    // 发送axios获取信息渲染页面
    async  loadEmployeeList() {
      const res = await getEmployeeList(this.page, this.size)
      if (res.code === 10000) {
        this.list = res.data.rows
        this.total = res.data.total
      }
    }
  }

}

</script>
